# -*- coding: utf-8 -*-
"""
-----------------------------------------------------------------
    File Name   : log.py
    Description : 日志处理程序
    Author      : DuanGe
    Created On  : 2024/11/19
    Email       : duangeali@aliyun.com
    Version     : 1.0.0
    Copyright   : Copyright (c) 2024 DuanGe
    License     : Apache License 2.0
-----------------------------------------------------------------
"""
import logging.config
import os

from . import constant

# 创建logs文件夹
if not os.path.exists(constant.LOGS_FILE_PATH):
    os.makedirs(constant.LOGS_FILE_PATH)

# 日志配置字典
log_config = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "simple": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S"
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "simple",
            "stream": "ext://sys.stdout"
        },
        "timed_rotating_file": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "level": "DEBUG",
            "formatter": "simple",
            "filename": "./logs/app.log",
            "encoding": "utf-8",
            "when": "midnight",
            "interval": 1,
            "backupCount": 10
        }
    },
    "loggers": {
        "file": {
            "level": "DEBUG",
            "handlers": [
                "timed_rotating_file"
            ],
            "propagate": False
        },
        "request": {
            "level": "DEBUG",
            "handlers": [
                "timed_rotating_file"
            ],
            "propagate": False
        },
        "table": {
            "level": "DEBUG",
            "handlers": [
                "timed_rotating_file"
            ],
            "propagate": False
        },
        "action": {
            "level": "DEBUG",
            "handlers": [
                "timed_rotating_file"
            ],
            "propagate": False
        }
    }
}

# 加载配置
logging.config.dictConfig(log_config)

# 文件日志记录器
file_logger = logging.getLogger('file')
# 请求日志记录器
request_logger = logging.getLogger('request')
# 表格日志记录器
table_logger = logging.getLogger('table')
# 操作日志记录器
action_logger = logging.getLogger('action')

# 日志级别
levelSet = frozenset(["INFO", "ERROR"])


def add_logs(recorder: logging.Logger, level: str, operation: str, msg: str = '',
             err_msg: str = '', exc_e: Exception = None, exc_info: bool = True):
    """
    添加日志

    :param recorder: 记录器
    :param level: 日志级别(INFO/ERROR)
    :param operation: 操作
    :param msg: 日志消息
    :param err_msg: 错误消息
    :param exc_e: 异常对象
    :param exc_info: 是否记录异常信息堆栈跟踪信息
    """
    level_upper = str(level).upper()
    # 检查日志级别是否有效
    if level_upper not in levelSet:
        raise ValueError("无效的日志级别")
    if level_upper == "INFO":
        # TODO 添加 stack_info=True 开启调用栈信息帮助追踪日志记录的位置(recorder.error同理)
        # recorder.info(operation_part + msg_part, stack_info=True)
        operation_part = operation + "成功"
        msg_part = "" if msg == '' else f", {msg}"
        recorder.info(operation_part + msg_part)
    if level_upper == "ERROR":
        operation_part = operation + "失败"
        err_msg_part = "" if err_msg == '' else f": {err_msg}"
        msg_part = "" if msg == '' else f", {msg}"
        exception_part = "" if exc_e is None else f", 错误信息: {type(exc_e).__name__} - {exc_e}"
        recorder.error(operation_part + err_msg_part + msg_part + exception_part, exc_info=exc_info)
